
package com.zhu.salesmanagement.views;

import java.util.ArrayList;

import com.zhu.location.R;
import com.zhu.salesmanagement.DealerTaskListActivity;
import com.zhu.salesmanagement.InputMessageActivity;
import com.zhu.salesmanagement.ProductInfoListActivity;
import com.zhu.salesmanagement.adapters.ProductInfoListAdapter;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.models.GoodsType;
import com.zhu.salesmanagement.models.ProductInfo;
import com.zhu.salesmanagement.models.VisitTaskInfo;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.Util;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.Color;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

public class ProductInfoListView extends LinearLayout implements View.OnClickListener {

    private final static int P_LIST_QUERY_TOKEN = 998;
    private final static int CP_LIST_QUERY_TOKEN = 999;
    private final static int CPNAME_LIST_QUERY_TOKEN = 997;
    private final static int GOODS_LIST_QUERY_TOKEN = 1000;
    private final static int GOODS_LIST_DELETE_TOKEN = 2000;
    public final static int INVALID_VALUE = -100;
    private final static int TYPE_FLOOR = 100;
    private final static int TYPE_SIDE = 101;
    private final static String TAG = "zhu";
    public final static String SPLIT_ROW = ";";
    public final static String SPLIT_RANK = "&";
    public final static String DEFAULT = "default";

    private Spinner mSpinner = null;
    private EditText mPlaceText = null;
    private EditText mFloorText = null;
    private EditText mSideText = null;
    private boolean isFirst = true;
    private ArrayList<GoodsType> mGoodsTypeList = new ArrayList<GoodsType>();
    private ScrollView mScrollView = null;
    private LinearLayout mBodyView = null;
    private ArrayList<ProductInfo> lists = new ArrayList<ProductInfo>();
    private ProductInfoListAdapter mProductInfoListAdapter = null;
    private TextView mInfoTextView = null;
    private GoodsListQueryHandler mGoodsListQueryHandler = null;
    private int mCurrentTypeIndex = 0;
    private int mLastTypeIndex = 0;
    private String mGoodsId = "0";

    private int mGoodsFloor = INVALID_VALUE;
    private int mGoodsSide = INVALID_VALUE;
    private int mGoodsPlace = INVALID_VALUE;
    private long mDBId = INVALID_VALUE;
    private ProductInfoListActivity mProductInfoListActivity = null;
    private VisitTaskInfo mVisitTaskInfo = null;
    private TextView mRemindTextView = null;
    private TextView mTitleTextView = null;

    public ProductInfoListView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public ProductInfoListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onFinishInflate() {
        setupViews();
        super.onFinishInflate();
    }

    private void setupViews() {
        // layout = (HorizontalScrollView) findViewById(R.id.layout);
        mScrollView = (ScrollView) findViewById(R.id.productinfolist_scrollview);
        mSpinner = (Spinner) findViewById(R.id.productSpinner);
        mInfoTextView = (TextView) findViewById(R.id.infoTextView);
        mBodyView = (LinearLayout) findViewById(R.id.productinfolistview_bodyView);
        mPlaceText = (EditText) findViewById(R.id.productinfo_seat);
        mFloorText = (EditText) findViewById(R.id.productinfo_floor);
        mSideText = (EditText) findViewById(R.id.productinfo_side);
        mRemindTextView = (TextView) findViewById(R.id.productedit_remindname);
        mTitleTextView = (TextView) findViewById(R.id.productedit_title);

        findViewById(R.id.productedit_back).setOnClickListener(this);

        findViewById(R.id.productinfo_chanpin).setOnClickListener(this);
        findViewById(R.id.productinfo_zhongyao).setOnClickListener(this);
        findViewById(R.id.productinfo_jingpin).setOnClickListener(this);
        findViewById(R.id.productinfo_delete).setOnClickListener(this);
        findViewById(R.id.productinfo_save2).setOnClickListener(this);
    }

    private void reset() {
        mDBId = INVALID_VALUE;
        mGoodsFloor = INVALID_VALUE;
        mGoodsSide = INVALID_VALUE;
        mGoodsPlace = INVALID_VALUE;

        startProductListAsyncQuery(mGoodsTypeList.get(mCurrentTypeIndex).typeId);
        //initListData();
        //startGoodsListAsyncQuery(mGoodsId, mGoodsTypeList.get(mCurrentTypeIndex).typeId);
    }

    public void initData(VisitTaskInfo visitTaskInfo,
            ProductInfoListActivity productInfoListActivity) {
        mVisitTaskInfo = visitTaskInfo;
        mProductInfoListActivity = productInfoListActivity;
        if (Actions.DEBUG) {
            Log.e("zhu", "GoodsId=" + mVisitTaskInfo.id);
        }
        mGoodsId = mVisitTaskInfo.id;
        mGoodsListQueryHandler = new GoodsListQueryHandler(getContext().getContentResolver());
        mRemindTextView.setText(getRemindText(mGoodsId));
        mTitleTextView.setText(mVisitTaskInfo.mName + getContext().getString(R.string.mendian));
        //initSpinner();
        //initListData();
        //startGoodsListAsyncQuery(mGoodsId, mGoodsTypeList.get(0).typeId);
        startCPsListAsyncQuery(mGoodsId);
    }

    private void startCPsListAsyncQuery(String goodsId){
        try {
            mGoodsListQueryHandler.startQuery(CP_LIST_QUERY_TOKEN, null,
                    SalesSettings.ProductShelfsColumns.CONTENT_URI,
                    null, SalesSettings.ProductShelfsColumns.CUSTOMER_ID + "=\"" + goodsId +"\"", null, null);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    private void startProductListAsyncQuery(String cpid){
        try {
            mGoodsListQueryHandler.startQuery(P_LIST_QUERY_TOKEN, null,
                    SalesSettings.ProductsColumns.CONTENT_URI,
                    null, SalesSettings.ProductsColumns.PRODUCTCATEGORY_ID + " = \"" + cpid +"\"", null, null);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    private void startCPNameListAsyncQuery(String where){
        try {
            mGoodsListQueryHandler.startQuery(CPNAME_LIST_QUERY_TOKEN, null,
                    SalesSettings.ProductCategoryColumns.CONTENT_URI,
                    null, where, null, null);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    public void updateDbId(long id){
        mDBId = id;
    }

    private void initSpinner() {
        String[] name = new String[mGoodsTypeList.size()];
        for (int i = 0; i < name.length; i++) {
            name[i] = mGoodsTypeList.get(i).typeName;
        }
        ArrayAdapter adapter = new ArrayAdapter<String>(this.getContext(),
                android.R.layout.simple_spinner_item, name);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinner.setAdapter(adapter);
        mSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                TextView tv = (TextView)arg1;
                tv.setTextColor(getResources().getColor(R.color.white));
                mLastTypeIndex = mCurrentTypeIndex;
                mCurrentTypeIndex = arg2;
                if (!isFirst) {
                    saveCurrentGoodsInfo(mLastTypeIndex);
                    reset();
                } else {
                    isFirst = false;
                    mLastTypeIndex = mCurrentTypeIndex;
                }
                // saveCurrentGoodsInfo();
                // reset();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });
    }

    private void intiGoodsTypeList(Cursor cursor) {
        if (mGoodsTypeList != null) {
            mGoodsTypeList.clear();
        }
        String where = "";
        try {
            final int pcIdIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductShelfsColumns.PRODUCTCATEGORY_ID);
            final int scountIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_COUNT);
            final int slayerIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_LAYER);
            final int sareaIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_AREA);

            while (cursor.moveToNext()) {
                GoodsType item = new GoodsType();
                item.typeId = cursor.getString(pcIdIndex);
                item.sArea = cursor.getString(sareaIndex);
                item.sLayer = cursor.getString(slayerIndex);
                item.sCount = cursor.getString(scountIndex);
                mGoodsTypeList.add(item);
                if(where.length() == 0){
                    where = SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID +" = \"" + item.typeId + "\"";
                }else{
                    where += " or " + SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID +" = \"" + item.typeId + "\"";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "intiGoodsTypeList error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }

        if(mGoodsTypeList.size() > 0){
            startCPNameListAsyncQuery(where);
            startProductListAsyncQuery(mGoodsTypeList.get(mCurrentTypeIndex).typeId);
        }
    }

    private void intiGoodsTypeNameList(Cursor cursor){
        try {
            final int pcIdIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID);
            final int pcNameIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_NAME);

            while (cursor.moveToNext()) {
                GoodsType item = getGoodsType(cursor.getString(pcIdIndex));
                item.typeName = cursor.getString(pcNameIndex);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "intiGoodsTypeNameList error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }
        initSpinner();
    }

    private GoodsType getGoodsType(String typeid){
        for(int i =0; i < mGoodsTypeList.size(); i++){
            GoodsType type = mGoodsTypeList.get(i);
            if(type.typeId.equals(typeid)){
                return type;
            }
        }
        return null;
    }

    private void initProductListData(Cursor cursor) {
        lists.clear();

        try {
            final int pcIdIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductsColumns.PRODUCTCATEGORY_ID);
            final int pidIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductsColumns.PRODUCT_ID);
            final int pnameIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductsColumns.PRODUCT_NAME);

            while (cursor.moveToNext()) {
                ProductInfo info = new ProductInfo();
                info.id = Integer.parseInt(cursor.getString(pidIndex));
                info.mName = cursor.getString(pnameIndex);
                lists.add(info);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "initProductListData error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }
        //if(lists.size() > 0){
            startGoodsListAsyncQuery(mGoodsId, mGoodsTypeList.get(mCurrentTypeIndex).typeId);
        //}else{
            updateBodyView();
            //updateProductInfoView(mGoodsTypeList.get(mCurrentTypeIndex).typeName, mGoodsPlace, mGoodsFloor, mGoodsSide);
        //}
    }

    private void updateListData(Cursor cursor) {
        try {
            final int idIndex = cursor.getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns._ID);
            final int placeIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns.PLACE);
            final int floorIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns.FLOOR);
            final int sideIndex = cursor.getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns.SIDE);
            final int goodsIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns.GOODS);

            while (cursor.moveToNext()) {
                mDBId = cursor.getLong(idIndex);
                if(lists.size() > 0){
                    String goods = cursor.getString(goodsIndex);
                    parseGoods(goods);
                }
                mGoodsFloor = cursor.getInt(floorIndex);
                mGoodsSide = cursor.getInt(sideIndex);
                mGoodsPlace = cursor.getInt(placeIndex);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "updateListData error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }

        updateBodyView();
        updateProductInfoView(mGoodsTypeList.get(0).typeName, mGoodsPlace, mGoodsFloor, mGoodsSide);
    }

    private void updateBodyView() {
        if (mBodyView != null) {
            mBodyView.removeAllViews();
        }
        for (int i = 0; i < lists.size(); i++) {
            ProductInfo info = lists.get(i);
            View v = getView(info, i);
            mBodyView.addView(v);
        }
    }

    private View getView(ProductInfo info, int index) {
        View view = LayoutInflater.from(this.getContext()).inflate(R.layout.productinfolist_item,
                null);
        view.setTag(info);
        view.setBackgroundColor(Color.WHITE);
        updateViews(view, index, info, false);
        return view;
    }

    private void updateViews(View view, int index, ProductInfo info, boolean isSetListener) {
        TextView textView1 = (TextView) view.findViewById(R.id.text1);
        Button textView2 = (Button) view.findViewById(R.id.text2);
        textView2.setOnClickListener(this);
        textView2.setTag(info);
        Button textView3 = (Button) view.findViewById(R.id.text3);
        textView3.setOnClickListener(this);
        textView3.setTag(info);
        EditText textView4 = (EditText) view.findViewById(R.id.text4);
        EditText textView5 = (EditText) view.findViewById(R.id.text5);

        textView1.setText(info.mName);
        textView2.setText(info.mFloor);
        textView3.setText(info.mSide);
        textView4.setText(info.mStock);
        textView5.setText(info.mPrice);

    }

    private void parseGoods(String goods) {
        if (Actions.DEBUG) {
            Log.e("zhu", "goods=" + goods);
        }
        String[] rowGoods = goods.split(SPLIT_ROW);
        for (int i = 0; i < rowGoods.length; i++) {
            if (Actions.DEBUG) {
                Log.e("zhu", "xx=" + rowGoods[i]);
            }
            String[] rankGoods = rowGoods[i].split(SPLIT_RANK);
            ProductInfo temInfo = getProductInfo(Integer.parseInt(rankGoods[0]));
            if (rankGoods[1].equals(DEFAULT)) {
                rankGoods[1] = "";
            }
            if (rankGoods[2].equals(DEFAULT)) {
                rankGoods[2] = "";
            }
            if (rankGoods[3].equals(DEFAULT)) {
                rankGoods[3] = "";
            }
            if (rankGoods[4].equals(DEFAULT)) {
                rankGoods[4] = "";
            }
            temInfo.mFloor = rankGoods[1];
            temInfo.mSide = rankGoods[2];
            temInfo.mStock = rankGoods[3];
            temInfo.mPrice = rankGoods[4];
        }
    }

    private ProductInfo getProductInfo(int id) {
        for (int i = 0; i < lists.size(); i++) {
            if (lists.get(i).id == id) {
                return lists.get(i);
            }
        }
        return null;
    }

    private void updateProductInfoView(String name, int seat, int floor, int side) {
        if (mInfoTextView != null) {
            mInfoTextView.setText(getResources().getString(R.string.productinfo));
        }
        if (seat != INVALID_VALUE) {
            mPlaceText.setText(String.valueOf(seat));
        } else {
            String sCount = mGoodsTypeList.get(mCurrentTypeIndex).sCount;
            if(sCount != null && sCount.length() > 0){
                mPlaceText.setText(sCount);
            }else{
                mPlaceText.setText("");
            }
        }
        if (side != INVALID_VALUE) {
            mSideText.setText(String.valueOf(side));
        } else {
            String area = mGoodsTypeList.get(mCurrentTypeIndex).sArea;
            if(area != null && area.length() > 0){
                mSideText.setText(area);
            }else{
                mSideText.setText(String.valueOf(getContext().getResources().getInteger(R.integer.config_defaultside)));
            }
        }
        if (floor != INVALID_VALUE) {
            mFloorText.setText(String.valueOf(floor));
        } else {
            String layer = mGoodsTypeList.get(mCurrentTypeIndex).sLayer;
            if(layer != null && layer.length() > 0){
                mFloorText.setText(layer);
            }else{
                mFloorText.setText(String.valueOf(getContext().getResources().getInteger(R.integer.config_defaultfloor)));
            }
        }
    }

    private void startGoodsListAsyncQuery(String storeid, String typeid) {
        try {
            mGoodsListQueryHandler.startQuery(GOODS_LIST_QUERY_TOKEN, null,
                    SalesSettings.GoodsInfoColumns.CONTENT_URI,
                    null, "storeid=? and typeid=?", new String[] {
                            storeid, typeid
                    }, null);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    private final class GoodsListQueryHandler extends AsyncQueryHandler {
        public GoodsListQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case CP_LIST_QUERY_TOKEN:
                    intiGoodsTypeList(cursor);
                    break;
                case CPNAME_LIST_QUERY_TOKEN:
                    intiGoodsTypeNameList(cursor);
                    break;
                case P_LIST_QUERY_TOKEN:
                    initProductListData(cursor);
                    break;
                case GOODS_LIST_QUERY_TOKEN:
                    updateListData(cursor);
                    break;
                default:
                    Log.e(TAG, "onQueryComplete called with unknown token " + token);
            }
        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {
            switch (token) {
                case GOODS_LIST_DELETE_TOKEN:
                    break;
                default:
                    Log.e(TAG, "onDeleteComplete called with unknown token " + token);
            }
        }
    }

    private void saveCurrentGoodsInfo(int index) {
        String placetext = mPlaceText.getText().toString().trim();
        if (placetext == null || placetext.length() < 1) {
            mGoodsPlace = INVALID_VALUE;
        } else {
            mGoodsPlace = Integer.valueOf(placetext);
        }

        String sidetext = mSideText.getText().toString().trim();
        if (sidetext == null || sidetext.length() < 1) {
            mGoodsSide = INVALID_VALUE;
        } else {
            mGoodsSide = Integer.valueOf(sidetext);
        }

        String floortext = mFloorText.getText().toString().trim();
        if (floortext == null || floortext.length() < 1) {
            mGoodsFloor = INVALID_VALUE;
        } else {
            mGoodsFloor = Integer.valueOf(floortext);
        }

        ContentValues values = new ContentValues();
        ContentResolver cr = this.getContext().getContentResolver();
        values.put(SalesSettings.GoodsInfoColumns.STOREID, mGoodsId);
        values.put(SalesSettings.GoodsInfoColumns.TYPEID, mGoodsTypeList.get(index).typeId);
        values.put(SalesSettings.GoodsInfoColumns.PLACE, mGoodsPlace);
        values.put(SalesSettings.GoodsInfoColumns.SIDE, mGoodsSide);
        values.put(SalesSettings.GoodsInfoColumns.FLOOR, mGoodsFloor);
        values.put(SalesSettings.GoodsInfoColumns.GOODS, getGoods());
        if (mDBId == INVALID_VALUE) {
            cr.insert(SalesSettings.GoodsInfoColumns.CONTENT_URI, values);
        } else {
            values.put(SalesSettings.GoodsInfoColumns._ID, mDBId);
            cr.update(SalesSettings.GoodsInfoColumns.getContentUri(mDBId, false), values, null,
                    null);
        }
    }

    public void saveData(boolean isFinish) {
        try{
            saveCurrentGoodsInfo(mCurrentTypeIndex);
            Actions.toastShort(getContext(), getContext().getString(R.string.save_success));
            if(isFinish){
            	mProductInfoListActivity.finish();
            }
        }catch(Exception e){
            Actions.toastShort(getContext(), getContext().getString(R.string.save_failed));
        }
    }

    private String getGoods() {
        String content = "";
        ProductInfo temInfo = null;
        View view = null;
        for (int i = 0; i < mBodyView.getChildCount(); i++) {
            view = mBodyView.getChildAt(i);
            temInfo = (ProductInfo) view.getTag();
            if (temInfo.id == INVALID_VALUE) {
                continue;
            }
            updateProductInfoFormView(temInfo, view);
            if (temInfo.mFloor == null || temInfo.mFloor.trim().length() < 1) {
                temInfo.mFloor = DEFAULT;
            }
            if (temInfo.mSide == null || temInfo.mSide.trim().length() < 1) {
                temInfo.mSide = DEFAULT;
            }
            if (temInfo.mStock == null || temInfo.mStock.trim().length() < 1) {
                temInfo.mStock = DEFAULT;
            }
            if (temInfo.mPrice == null || temInfo.mPrice.trim().length() < 1) {
                temInfo.mPrice = DEFAULT;
            }
            String row = temInfo.id + SPLIT_RANK + temInfo.mFloor + SPLIT_RANK +
                    temInfo.mSide + SPLIT_RANK + temInfo.mStock + SPLIT_RANK + temInfo.mPrice;
            content += (row + SPLIT_ROW);
        }
        return content;
    }

    private void updateProductInfoFormView(ProductInfo info, View view) {
        Button textView2 = (Button) view.findViewById(R.id.text2);
        info.mFloor = textView2.getText().toString().trim();
        Button textView3 = (Button) view.findViewById(R.id.text3);
        info.mSide = textView3.getText().toString().trim();
        EditText textView4 = (EditText) view.findViewById(R.id.text4);
        info.mStock = textView4.getText().toString().trim();
        EditText textView5 = (EditText) view.findViewById(R.id.text5);
        info.mPrice = textView5.getText().toString().trim();
    }

    private void showSaveDialog() {
        Dialog alertDialog = new AlertDialog.Builder(this.getContext())
                .setTitle(R.string.save_title)
                .setMessage(R.string.save_content)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setPositiveButton(R.string.queding, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                    }
                }).create();
        alertDialog.show();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v != null) {
            switch (v.getId()) {
                case R.id.productedit_back:
                    mProductInfoListActivity.finish();
                    break;
                case R.id.productinfo_zhongyao:
                    gotoImportActivity();
                    break;
                case R.id.productinfo_jingpin:
                    gotoJinpinActivity();
                    break;
                case R.id.productinfo_save2:
                    saveData(true);
                    break;
                case R.id.text3:
                    popDialog((Button)v, TYPE_SIDE);
                    break;
                case R.id.text2:
                    popDialog((Button)v, TYPE_FLOOR);
                    break;
                case R.id.productinfo_delete:
                    popDeleteDialog();
                    break;
            }
        }
    }

    private void gotoImportActivity() {
        if(mGoodsTypeList.size() == 0){
            Actions.toastShort(getContext(), getContext().getString(R.string.noteditinfo));
            return;
        }
        Intent intent = new Intent(mProductInfoListActivity, InputMessageActivity.class);
        intent.putExtra("type", ImportantInfoView.TYPE_ZHONGYAO);
        intent.putExtra("protype", mGoodsTypeList.get(mCurrentTypeIndex).typeId);
        intent.putExtra("dbid", mDBId);
        Bundle bundle = new Bundle();
        bundle.putParcelable("info", mVisitTaskInfo);
        intent.putExtras(bundle);
        mProductInfoListActivity.startActivityForResult(intent, ProductInfoListActivity.UPDATE_DB);
    }

    private void gotoJinpinActivity() {
        if(mGoodsTypeList.size() == 0){
            Actions.toastShort(getContext(), getContext().getString(R.string.noteditinfo));
            return;
        }
        Intent intent = new Intent(mProductInfoListActivity, InputMessageActivity.class);
        intent.putExtra("type", ImportantInfoView.TYPE_JINPIN);
        intent.putExtra("protype", mGoodsTypeList.get(mCurrentTypeIndex).typeId);
        intent.putExtra("dbid", mDBId);
        Bundle bundle = new Bundle();
        bundle.putParcelable("info", mVisitTaskInfo);
        intent.putExtras(bundle);
        mProductInfoListActivity.startActivityForResult(intent, ProductInfoListActivity.UPDATE_DB);
    }

    private void popDialog(final Button button, int type){
        int maxCount = 0;
        int titleid = 0;

        if(type == TYPE_SIDE){
            titleid = R.string.selectside;
            String side = mSideText.getText().toString().trim();
            if(side != null && side.length() > 0){
                maxCount = Integer.parseInt(side);
            }
        }else{
            titleid = R.string.selectfloor;
            String floor = mFloorText.getText().toString().trim();
            if(floor != null && floor.length() > 0){
                maxCount = Integer.parseInt(floor);
            }
        }
        if(maxCount == 0){
            Actions.toastShort(getContext(), getContext().getString(R.string.writestoreinfo));
            return;
        }

        final String[] dataArray = new String[maxCount];
        for(int i = 1; i < dataArray.length + 1; i++){
            dataArray[i-1] = String.valueOf(i);
        }
        new AlertDialog.Builder(getContext())
        .setTitle(titleid)
        .setItems(dataArray,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {
                        button.setText(dataArray[which]);
                    }
                }).show();
    }

    private void popDeleteDialog() {
        Actions.alertShowDetails(getContext(), getContext().getString(R.string.stopbusinessclew),
                getContext().getString(R.string.stopbusinesscontent),
                R.string.queding, R.string.cancel,
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                    	boolean success = Util.saveStoresClose(ProductInfoListView.this.getContext(), mVisitTaskInfo.mDbId);
                    	if(success){
                    		mProductInfoListActivity.setResult(ProductInfoListActivity.RESULT_OK);
                    		mProductInfoListActivity.finish();
                    	}
                    }
                }, new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {

                    }
                });
    }

    private String getRemindText(String cid){
        String remindtext = null;
        Cursor cursor = null;
        try{
            String where = SalesSettings.RemindsColumns.CUSTOMERID + " = \'" + cid +"\'";
            cursor = getContext().getContentResolver().query(SalesSettings.RemindsColumns.CONTENT_URI_NO_NOTIFICATION, null, where, null, null);
            while (cursor.moveToNext()) {
                String text = cursor.getString(cursor.getColumnIndexOrThrow(SalesSettings.RemindsColumns.TEXT));
                if(text != null && text.length() > 0){
                    remindtext = text;
                    break;
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            remindtext = null;
        }finally{
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        if(remindtext == null){
            remindtext = this.getContext().getString(R.string.noremind);
        }
        return remindtext;
    }
}
